package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exceptions.LyException;
import com.leyou.item.dto.SkuDTO;
import com.leyou.item.entity.Sku;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.service.SkuService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SkuServiceImpl extends ServiceImpl<SkuMapper, Sku> implements SkuService {
    private static final String UPDATE_STOCK_STATEMENT = "com.leyou.item.mapper.SkuMapper.deductStock";
    private static final String PLUS_STOCK_STATEMENT = "com.leyou.item.mapper.SkuMapper.plusStock";
    //根据spuID查询sku的集合
    @Override
    public List<SkuDTO> SkuByIds(List<Long> ids) {
        List<Sku> skuList = listByIds(ids);
        return SkuDTO.convertEntityList(skuList);
    }

    @Override
    public List<SkuDTO> listSkuByID(Long id) {
        List<Sku> spuId = query().eq("spu_id", id).list();
        return SkuDTO.convertEntityList(spuId);
    }

    @Override
    public List<SkuDTO> queryById(Long id) {
        // 3.查询sku
        List<Sku> list =query().eq("spu_id", id).list();
        if(CollectionUtils.isEmpty(list)){
            throw new LyException(400, "商品id不存在！");
        }
        return SkuDTO.convertEntityList(list);
    }

    //减库存
    @Override
    @Transactional
    public void deductStock(Map<Long, Integer> skuMap) {
        //遍历sku


//            //查询sku
//            Sku sku = getById(skuid);
//            //判断库存
//            if (sku.getStock()<num){
//                throw new LyException(400,"库存不足");
//            }
//            //库存充足，可以折扣
//            update().set("stock",sku.getStock()-num).set("sold",sku.getSold()+num)
//                    .eq("id",skuid).update();
//        for (Map.Entry<Long, Integer> entry : skuMap.entrySet()) {
//            Map<String,Object> param=new HashMap<>();
//            param.put("id",entry.getKey());
//            param.put("num",entry.getValue());
//            int count = getBaseMapper().deductStock(param);
//            if (count==0){
//                throw new LyException(400,"更新库失败或者商品已经下架");
//            }

        executeBatch(sqlSession -> {
            for (Map.Entry<Long, Integer> entry : skuMap.entrySet()) {
                Map<String,Object> param=new HashMap<>();
                param.put("id",entry.getKey());
                param.put("num",entry.getValue());
               sqlSession.update(UPDATE_STOCK_STATEMENT,param);
            }
            sqlSession.flushStatements();
        });

    }

    @Override
    @Transactional
    public void plusStock(Map<Long, Integer> skuMap) {

        try {
            executeBatch(sqlSession -> {
                // 遍历sku
                for (Map.Entry<Long, Integer> entry : skuMap.entrySet()) {
                    // 调用mapper中的方法
                    Map<String, Object> param = new HashMap<>();
                    param.put("id", entry.getKey());
                    param.put("num", entry.getValue());
                    // 编译Sql，第一个参数：可以是sql，也可以是statementId：mapper接口名.方法名
                    // 第二个参数是sql需要的参数
                    sqlSession.update(PLUS_STOCK_STATEMENT, param);
                }
                // 刷新和提交
                sqlSession.flushStatements();
            });
        } catch (Exception e) {
            throw new LyException(400, e.getMessage());
        }
    }
}



